package org.idea.spring.framework.mybatis.config;

import org.apache.catalina.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.idea.spring.framework.mybatis.mapper.IdMapper;
import org.idea.spring.framework.mybatis.mapper.UserMapper;
import org.idea.spring.framework.mybatis.po.Id;
import org.idea.spring.framework.mybatis.properties.MybatisProperties;
import org.idea.spring.framework.mybatis.utils.AnnotationUtils;
import org.idea.spring.framework.mybatis.utils.EnvironmentUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Author linhao
 * @Date created in 11:08 下午 2021/6/4
 */
@org.springframework.context.annotation.Configuration
public class MybatisConfigRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    private MybatisProperties mybatisProperties;

    private Environment environment;

    private static final String DEFAULT_DATASOURCE_PREFIX = "idea.mybatis";

    private static SqlSessionFactory sqlSessionFactory;

    private static SqlSession sqlSession;

    private static Set<Class> mapperClassSet = new HashSet<>();

    public static SqlSession getSqlSession() {
        return sqlSession;
    }

    public static Set<Class> getMapperClassSet() {
        return mapperClassSet;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        try {
            this.initMyBatisProperties();
            this.initSqlSessionFactory();
            System.out.println("初始化结束");
            //todo 初始化一些mybatis的sqlsessionFactory
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initSqlSessionFactory() {
        PooledDataSource pooledDataSource = new PooledDataSource();
        pooledDataSource.setUrl(this.mybatisProperties.getUrl());
        pooledDataSource.setUsername(this.mybatisProperties.getUsername());
        pooledDataSource.setPassword(this.mybatisProperties.getPassword());
        pooledDataSource.setDriver(this.mybatisProperties.getDriver());
        pooledDataSource.setDefaultAutoCommit(false);
        TransactionFactory transactionFactory = new JdbcTransactionFactory();

        org.apache.ibatis.mapping.Environment environment = new org.apache.ibatis.mapping.Environment("dev", transactionFactory, pooledDataSource);
        Configuration configuration = new Configuration(environment);

        Set<Class> classSet = AnnotationUtils.getClassFromPackageWithAnnotation(this.mybatisProperties.getBaseMapperPkg(), Mapper.class);
        for (Class mapperClass : classSet) {
            mapperClassSet.add(mapperClass);
            configuration.addMapper(mapperClass);
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        sqlSession = sqlSessionFactory.openSession();
    }

    /**
     * 初始化容器内部的配置属性
     */
    private void initMyBatisProperties() throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        mybatisProperties = new MybatisProperties();
        Map<String, String> propertiesMap = EnvironmentUtils.getSubProperties(environment, DEFAULT_DATASOURCE_PREFIX);
        for (String key : propertiesMap.keySet()) {
            PropertyDescriptor propertyDescriptor = new PropertyDescriptor(key, MybatisProperties.class);
            Method method = propertyDescriptor.getWriteMethod();
            method.invoke(mybatisProperties, propertiesMap.get(key));
        }
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
